/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gerenciadorfinanceiro.ejb.session;

import org.gerenciadorfinanceiro.ejb.session.interfaces.UsuarioSessionLocal;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.gerenciadorfinanceiro.ejb.entity.User;
import org.gerenciadorfinanceiro.ejb.session.interfaces.UsuarioSessionRemote;

/**
 *
 * @author eduardo
 */
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class UsuarioSessionBean implements UsuarioSessionLocal, UsuarioSessionRemote {

    @PersistenceContext
    private EntityManager entityManager;

    public void addUsuario(User user) throws BusinessViolation {
        validateUser(user);

        if (this.getUsuario(user.getNameUser()) != null) throw new BusinessViolation("Usuario ja existe.");

        entityManager.merge(user);
    }

    public void updateUsuario(User user) throws BusinessViolation {
        validateUser(user);
        
        if (this.getUsuario(user.getIdUser().intValue()) == null) {
            throw new BusinessViolation("Usuario inexistente.");
        }

        entityManager.merge(user);
    }

    public List<User> getUsuarios() {
        Query query = entityManager.createNamedQuery("User.findAll");
        return query.getResultList();
    }

    public User getUsuario(String nameUser) {
        Query query = entityManager.createNamedQuery("User.findByNameUser");
        query.setParameter("nameUser", nameUser);
        List<User> users = query.getResultList();

        if (users.size() > 0) {
            return users.get(0);
        } else {
            return null;
        }
    }

    public User getUsuario(int idUser) {
        return entityManager.find(User.class, new Integer(idUser));
    }

    public void deleteUsuario(User user) throws BusinessViolation {
        if (this.getUsuario(user.getIdUser().intValue()) == null) {
            throw new BusinessViolation("Usuario inexistente.");
        }

        User aux = entityManager.getReference(User.class, user.getIdUser());
        entityManager.remove(aux);
    }

    public boolean isUserAndPasswordValid(String login, String password) {
        User u = this.getUsuario(login);

        if (u != null) {
            if (u.getUserPassword().equals(UsuarioSessionBean.encrypt(password))) {
                return true;
            }
        }

        return false;
    }

    public static String encrypt(String password) {
        String sign = password;

        try {
            java.security.MessageDigest md =
                    java.security.MessageDigest.getInstance("MD5");
            md.update(sign.getBytes());
            byte[] hash = md.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                if ((0xff & hash[i]) < 0x10) {
                    hexString.append(
                            "0" + Integer.toHexString((0xFF & hash[i])));
                } else {
                    hexString.append(Integer.toHexString(0xFF & hash[i]));
                }
            }
            sign = hexString.toString();
        } catch (Exception nsae) {
            nsae.printStackTrace();
        }
        return sign;
    }

    public void validateUser(User u) throws BusinessViolation {
        boolean valid = true;
        String msg = "";

        if (u.getNameUser() == null || u.getNameUser().isEmpty()) {
            valid = false;
            msg = "Nome invalido.";
        }

        if (u.getUserPassword() == null || u.getUserPassword().isEmpty()) {
            valid = false;
            msg = "Senha invalida.";
        }

        if (! valid) {
            throw new BusinessViolation(msg);
        }

    }
}
